package com.yyds.blackmagic.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

/**
 * @Author ccc
 * @Date 2021/12/18
 * @Descripton
 */
public class QiNiuUtils {
    //构造一个带指定 Region 对象的配置类
    private static Configuration cfg = new Configuration (Region.huanan ());
    //...其他参数参考类注释
    private static UploadManager uploadManager = new UploadManager (cfg);
    //...生成上传凭证，然后准备上传
    private static String accessKey = VariableName.accessKey;
    private static String secretKey = VariableName.secretKey;
    private static String bucket = VariableName.bucket;
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    private static String key = null;
    private static Auth auth = Auth.create (accessKey, secretKey);
    private static String upToken = auth.uploadToken (bucket);

    public static String updateFile (MultipartFile file, String filename) throws Exception {
        try {
            byte[] uploadBytes = file.getBytes ();
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Response response = uploadManager.put(byteInputStream,filename,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson ().fromJson (response.bodyString (), DefaultPutRet.class);
            return VariableName.domain+putRet.key;
        } catch (
                QiniuException ex) {
            Response r = ex.response;
            System.err.println (r.toString ());
            try {
                System.err.println (r.bodyString ());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }
}
